import { get, post } from '@/api/http'
import Axios from 'axios'
import {
  adminList,
  getUserListN,
  setTableDepartment,
  getTableDepartment,
  deleteNumber,
  templatesList,
} from '@/api/url'
import {
  channel,
  series,
  encoding,
  recharge,
  speed,
  xuliangUrl,
  merchantType,
  getchannelList,
  getUserSeries,
  getUserList,
  typePay,
  payList,
  mealList,
  couponList,
  disconnection,
  oneCodeName,
} from '@/api/common'
import { defineStore } from 'pinia'
import qs from 'qs'
import store from '../pinia'
import { Message, Modal } from '@arco-design/web-vue'
import router from '@/router'
import one from '@/assets/flag/one.png'
import two from '@/assets/flag/two.png'
import three from '@/assets/flag/three.png'
import four from '@/assets/flag/four.png'
import five from '@/assets/flag/five.png'
import six from '@/assets/flag/six.png'

const useCommonStore = defineStore('common', {
  state: () => {
    return {
      flagList: [
        {
          type: 1,
          img: one,
        },
        {
          type: 2,
          img: two,
        },
        {
          type: 3,
          img: three,
        },
        {
          type: 4,
          img: four,
        },
        {
          type: 5,
          img: five,
        },
        {
          type: 6,
          img: six,
        },
      ],
      routerList: [],
      adminList: [],
      title: '首页',
      shopState: [
        {
          state: -2,
          name: '未知',
          color: '',
        },
        {
          state: -1,
          name: '删除',
          color: 'red',
        },
        {
          state: 0,
          name: '待处理',
          color: '',
        },

        {
          state: 1,
          name: '进行中',
          color: 'gold',
        },
        {
          state: 2,
          name: '已提交',
          color: 'blue',
        },

        {
          state: 3,
          name: '已发货',
          color: 'green',
        },
        {
          state: 4,
          name: '已失败',
          color: 'red',
        },
        {
          state: 5,
          name: '已退款',
          color: 'red',
        },
      ],
      state: [
        {
          state: -1,
          name: '未知',
          color: '',
        },
        {
          state: 1,
          name: '库存',
          color: '',
        },
        {
          state: 2,
          name: '待激活',
          color: 'gold',
        },

        {
          state: 5,
          name: '可测试',
          color: 'green',
        },
        {
          state: 0,
          name: '已激活',
          color: 'blue',
        },

        {
          state: 4,
          name: '已停机',
          color: 'red',
        },
        {
          state: 7,
          name: '已销户',
          color: 'red',
        },
        {
          state: 6,
          name: '机卡分离',
          color: 'red',
        },
        {
          state: 3,
          name: '风险停机',
          color: 'red',
        },
      ],
      error: [
        {
          state: 0,
          name: '单向停机',
          color: '',
          content: '更新下来就是停机状态系统未调用过',
        },

        {
          state: 2,
          name: '系统停机',
          color: 'gold',
          content: '因某种原因主动点击停机操作',
        },
        {
          state: 1,
          name: '没有订单',
          color: '',
          content: '系统没有订单但是状态是已激活',
        },
        {
          state: 5,
          name: '订单过期',
          color: 'green',
          content: '订单过期但是流量未使用完',
        },
        {
          state: 6,
          name: '负流量',
          color: 'green',
          content: '流量使用完但是订单未过期',
        },
        {
          state: 7,
          name: '负数过期',
          color: 'blue',
          content: '订单过期并且流量使用完',
        },
        {
          state: 8,
          name: '流量用完',
          color: 'red',
          content: '流量达到停机阈值但是订单没有过期',
        },
        {
          state: 9,
          name: '用完过期',
          color: 'red',
          content: '流量达到停机阈值并且订单过期',
        },
        {
          state: 10,
          name: '未续费',
          color: 'red',
          content: '没有提前续费但是订单未过期',
        },
        {
          state: 11,
          name: '未续过期',
          color: 'red',
          content: '没有提前续费并且订单过期了',
        },
        {
          state: 3,
          name: '注销停机',
          color: 'green',
          content: '因注销被系统执行停机',
        },
        {
          state: 4,
          name: '换卡停机',
          color: 'green',
          content: '因换卡被系统执行停机',
        },
        {
          state: 12,
          name: '达量断网',
          color: 'red',
          content: '流量达到达量断网阈值',
        },
      ],
    }
  },
  getters: {},
  actions: {
    getCityCodeByDistrictCode(districtCode: any, regions: any) {
      function traverse(data) {
        for (const province of data) {
          for (const cityOrDistrict of province.children) {
            if (
              cityOrDistrict.children &&
              cityOrDistrict.children.some((district) => district.code === districtCode)
            ) {
              return cityOrDistrict.code
            }
            if (cityOrDistrict.code === districtCode) {
              return province.code
            }
          }
        }
        return null
      }
      return traverse(regions)
    },
    calculateEffectiveAndExpiryDates(
      rechargeDateStr: any,
      packageDuration: any,
      validityType: any,
      effectiveType: any,
      clearType: any,
      type: any
    ) {
      // 将充值时间字符串转换为 Date 对象
      const rechargeDate = new Date(rechargeDateStr)

      let packageDurationNum
      if (type == true && validityType == 0) {
        packageDurationNum = 30 * packageDuration
      } else {
        packageDurationNum = packageDuration
      }

      // 确定生效时间
      let effectiveDate
      if (effectiveType === 1) {
        // 本月生效，生效时间为本月 1 号
        effectiveDate = rechargeDate
      } else {
        // 次月生效（仅月套餐支持），生效时间为充值时间的下一个月的对应日期
        effectiveDate = new Date(rechargeDate.getFullYear(), rechargeDate.getMonth() + 1, 1)
      }

      // 确定到期时间
      let expiryDate

      if (validityType === 0) {
        // 有效期类型为天
        expiryDate = new Date(effectiveDate.getTime() + packageDurationNum * 24 * 60 * 60 * 1000)
      } else if (validityType === 1) {
        if (effectiveType === 1) {
          // 本月生效，生效时间为本月 1 号
          console.log(clearType)
          if (clearType === 0) {
            // 月底清零，将到期时间调整为当月最后一天
            if (packageDurationNum > 1) {
              expiryDate = new Date(
                effectiveDate.getFullYear(),
                effectiveDate.getMonth() + packageDurationNum,
                0
              )
            } else {
              expiryDate = new Date(
                effectiveDate.getFullYear(),
                effectiveDate.getMonth() + packageDurationNum,
                0
              )
            }
          } else if (clearType === 1) {
            // 26 号清零，将到期时间调整为当月 26 号
            expiryDate = new Date(
              effectiveDate.getFullYear(),
              effectiveDate.getMonth() + packageDurationNum,
              26
            )
          }
        } else {
          // 本月生效，生效时间为本月 1 号
          if (clearType === 0) {
            // 月底清零，将到期时间调整为当月最后一天
            expiryDate = new Date(
              effectiveDate.getFullYear(),
              effectiveDate.getMonth() + packageDurationNum,
              0
            )
          } else if (clearType === 1) {
            // 26 号清零，将到期时间调整为当月 26 号
            expiryDate = new Date(
              effectiveDate.getFullYear(),
              effectiveDate.getMonth() + packageDurationNum,
              26
            )
          }
        }
      }
      // 将到期时间的时分秒设置为 23:59:59
      expiryDate.setHours(23)
      expiryDate.setMinutes(59)
      expiryDate.setSeconds(59)

      // 格式化日期为 YYYY-MM-DD 格式
      function formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }

      return {
        effectiveDate: formatDate(effectiveDate),
        expiryDate: formatDate(expiryDate),
      }
    },
    getAreaNamesByCode(code: any, areaData: any) {
      let provinceName = ''
      let cityName = ''
      let districtName = ''

      // 查找省份名称
      const province = areaData.find((element: any) => element.code === code.slice(0, 2) + '0000')
      if (province) {
        provinceName = province.name
        const citiesOrDistricts = province.children
        const isThreeLevel = citiesOrDistricts.some(
          (cityOrDistrict: any) => cityOrDistrict.children && cityOrDistrict.children.length > 0
        )
        if (isThreeLevel) {
          // 查找城市名称
          const city = citiesOrDistricts.find((element: any) => element.code === code)
          if (city) {
            cityName = city.name
            return provinceName + cityName
          } else {
            const citys = citiesOrDistricts.find(
              (element: any) => element.code === code.slice(0, 4) + '00'
            )
            if (citys) {
              cityName = citys.name
              const districts = citys.children
              // 查找区县名称
              const district = districts.find((c: any) => c.code === code)
              if (district) {
                districtName = district.name
              }
            }
            return provinceName + cityName + districtName
          }
        } else {
          // 查找区县名称（二级结构情况）
          const district = citiesOrDistricts.find((c: any) => c.code === code)
          if (district) {
            districtName = district.name
          }
          return provinceName + districtName
        }
      }
    },
    //渠道筛选
    filterTreeNode(searchValue: any, nodeData: any) {
      return nodeData.title.toLowerCase().indexOf(searchValue.toLowerCase()) > -1
    },
    //获取地区列表
    async getDistrictsList(val: any, val1?: any) {
      const res = await get({
        url: '/app/mall/getMallAddress',
        data: {
          level: val,
          handlerCity: val1 ? val1 : '',
        },
      })
      return res
    },
    //判断两个时间
    checkTimePeriodStatus(startDate: any) {
      const currentDate = new Date()
      const startDateTime = new Date(startDate)
      if (currentDate < startDateTime) {
        return 1
      } else {
        return 2
      }
    },
    copy(val: any) {
      const input = document.createElement('input')
      input.value = val
      input.id = 'creatDoms'
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      Message.success('复制成功')
    },
    //计算时间
    formatTimeDifference(seconds: any) {
      // 计算小时、分钟和秒
      const hours = Math.floor(seconds / 3600) // 整除得到小时数
      const minutes = Math.floor((seconds % 3600) / 60) // 整除得到分钟数
      const secs = seconds % 60 // 取余得到秒数

      // 格式化输出
      let result = ''
      if (hours > 0) {
        result += hours + '小时'
      }
      if (minutes > 0) {
        result += minutes + '分钟'
      }
      result += secs + '秒'

      return result
    },

    formatDateTime(date: any) {
      const year = date.getFullYear()
      const month = ('0' + (date.getMonth() + 1)).slice(-2)
      const day = ('0' + date.getDate()).slice(-2)
      const hours = ('0' + date.getHours()).slice(-2)
      const minutes = ('0' + date.getMinutes()).slice(-2)
      const seconds = ('0' + date.getSeconds()).slice(-2)

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    routerOne(val: any) {
      // const input = document.createElement('input')
      // input.value = val
      // input.id = 'creatDoms'
      // document.body.appendChild(input)
      // input.select()
      // document.execCommand('copy')
      // document.body.removeChild(input)
      // Message.success('复制成功')
      router.push('/card/single?card=' + val)
    },

    getTimeDifference(time1: any) {
      const date1 = new Date(time1) // time1为字符串形式的时间
      const date2 = new Date() // time2为字符串形式的时间
      const difference = Math.floor(date2.getTime() - date1.getTime()) // 计算两个时间戳的差值

      // 转换为小时、分钟和秒
      const day = Math.floor(difference / (1000 * 60 * 60 * 24))
      const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60))
      const s = Math.floor((difference % (60 * 1000 * 60)) / 1000)

      const dates1 = hours + '时' + minutes + '分'
      const date = day + '天' + hours + '时' + minutes + '分'
      const dates = minutes + '分 '
      const datea = s + '秒'

      return day > 0 ? date : hours > 0 ? dates1 : minutes >= 1 ? dates : s > 0 ? datea : '0秒'
    },
    getTimeDifferences(time1: any, time2: any) {
      const date1 = new Date(time1) // time1为字符串形式的时间
      const date2 = new Date(time2) // time2为字符串形式的时间
      const difference = date2.getTime() - date1.getTime() // 计算两个时间戳的差值

      // 转换为小时、分钟和秒
      const day = Math.floor(difference / (1000 * 60 * 60 * 24))
      const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) % 24
      const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)) % 60
      const s = Math.floor((difference % (60 * 1000 * 60)) / 1000) % 60

      const dates1 = hours + '时' + (minutes == 0 ? '' : minutes + '分') + (s == 0 ? '' : s + '秒')
      const date = day + '天' + hours + '时' + minutes + '分' + s + '秒'
      const dates = minutes + '分 ' + (s == 0 ? '' : s + '秒')
      const datea = s + '秒'

      return day > 0 ? date : hours > 0 ? dates1 : minutes >= 1 ? dates : s > 0 ? datea : '0秒'
    },
    getTimeDifferences1(time2: any, type: any) {
      const date1 = new Date() // time1为字符串形式的时间
      const date2 = new Date(time2) // time2为字符串形式的时间
      const difference = date2.getTime() - date1.getTime() // 计算两个时间戳的差值
      console.log(difference, '时间')
      // 转换为小时、分钟和秒
      if (type == 1) {
        const day = Math.floor(difference / (1000 * 60 * 60 * 24))
        return difference < 0 ? -1 : day
      } else {
        const hours = Math.floor(difference / (1000 * 60 * 60))
        return difference < 0 ? -1 : hours
      }
    },
    //流量单位换算
    numbers(val: number) {
      if (val < 1024) {
        return Math.floor(val * 100) / 100 + 'B'
      } else if (val > 1024 && val < 1024 * 1024) {
        return Math.floor((val / 1024) * 100) / 100 + 'K'
      } else if (val > 1024 * 1024 && val < 1024 * 1024 * 1024) {
        return Math.floor((val / (1024 * 1024)) * 100) / 100 + 'M'
      } else if (val > 1024 * 1024 * 1024 && val < 1024 * 1024 * 1024 * 1024) {
        return Math.floor((val / (1024 * 1024 * 1024)) * 100) / 100 + 'G'
      } else {
        return Math.floor((val / (1024 * 1024 * 1024 * 1024)) * 100) / 100 + 'T'
      }
    },

    //流量单位换算
    numbersa(val: number) {
      if (val < 1024) {
        return Math.floor(val * 100) / 100
      } else if (val > 1024 && val < 1024 * 1024) {
        return Math.floor((val / 1024) * 100) / 100
      } else if (val > 1024 * 1024 && val < 1024 * 1024 * 1024) {
        return Math.floor((val / (1024 * 1024)) * 100) / 100
      } else if (val > 1024 * 1024 * 1024 && val < 1024 * 1024 * 1024 * 1024) {
        return Math.floor((val / (1024 * 1024 * 1024)) * 100) / 100
      } else {
        return Math.floor((val / (1024 * 1024 * 1024 * 1024)) * 100) / 100
      }
    },

    //流量单位换算
    numbers1(val: number) {
      if (val >= 1024) {
        return Math.floor((val / 1024) * 100) / 100 + 'G'
      } else {
        return Math.floor(val * 100) / 100 + 'M'
      }
    },
    async titleName(value: any) {
      this.title = value
    },
    //重置
    async deleteNumber(val: any) {
      const res = await get({ url: deleteNumber, data: { name: val } })
      return res
    },

    //全部商品
    async mallFn() {
      const res = await get({ url: '/app/mall/name/list' })
      return returnFn(res, 'name')
    },

    //全部商品订单状态
    async orderStateFn() {
      const res = await get({ url: '/app/mall/release/order/get/state' })
      res.data.forEach((element: any) => {
        if (
          element.state == -1 ||
          element.state == 8 ||
          element.state == 18 ||
          element.state == 14 ||
          element.state == 4 ||
          element.state == 5 ||
          element.state == 17 ||
          element.state == 19
        ) {
          element.color = 'red'
        } else if (
          element.state == 1 ||
          element.state == 6 ||
          element.state == 7 ||
          element.state == 16
        ) {
          element.color = 'gold'
        } else if (
          element.state == 10 ||
          element.state == 11 ||
          element.state == 2 ||
          element.state == 13
        ) {
          element.color = 'blue'
        } else if (element.state == 3) {
          element.color = 'green'
        } else {
          element.color = ''
        }
        return res
      })
      return res
    },

    //代理全部商品
    async userMallFn() {
      const res = await get({ url: '/app/mall/user/get/mall/name/list' })
      return returnFn(res, 'name')
    },
    //获取全部装修方案
    async decorationFn() {
      const res = await get({ url: '/app/series/decoration/plan/name/list' })
      return res
    },
    //支付列表
    async getPayList(val: any) {
      const res = await get({ url: payList, data: { mode: val } })
      return res
    },
    //一卡一码列表
    async oneCodeNameFn() {
      const res = await get({ url: oneCodeName, data: {} })
      return res
    },
    //快递渠道
    async expressChannel() {
      const res = await get({
        url: '/app/mall/express/channel/coding/get/list',
      })
      return res
    },

    //代理客户列表
    async userListse() {
      const res = await get({ url: getUserList })
      return returnFn(res, 'userName')
    },
    //达量断网列表
    async disconnectionFn() {
      const res = await get({ url: disconnection })
      return res
    },

    //优惠券列表
    async couponListFn() {
      // const res = await get({ url: couponList })

      const res = fetch(couponList)
        .then((response) => response.json())
        .catch((error) => {
          if (error.msg == '插件未购买') {
          }
        })
      return res
    },
    //支付模板列表
    async templatesListFn(val?: any) {
      const res = await get({
        url: templatesList,
        data: {
          admin: val,
        },
      })
      return res
    },
    //获取支付类型
    async typePays() {
      const res = await get({ url: typePay })
      return res
    },
    //获取支付模板类型
    async merchantTypes() {
      const res = await get({ url: merchantType })
      return res
    },

    //获取预存方案列表
    async recharges() {
      const res = await get({ url: recharge })
      return res
    },
    //获取限速方案列表
    async speeds() {
      const res = await get({ url: speed })
      return res
    },
    //获取渠道编码列表
    async encodings() {
      const res = await get({ url: encoding })
      return res
    },

    //获取套餐列表
    async mealListFn(val?: any) {
      const res = await get({
        url: mealList,
        data: {
          seriesIds: val,
        },
      })
      return res
    },
    //代理获取套餐列表
    async usermealListFn() {
      const res = await get({ url: '/app/user/set/meal/get/name/list' })
      return res
    },
    //获取极速会员
    async speedVip() {
      // const res = await get({ url: '/app/speed/vip/get/name' })
      // return res

      const res = fetch('/app/speed/vip/get/name')
        .then((response) => response.json())
        .catch((error) => {
          if (error.msg == '插件未购买') {
          }
        })
      return res
    },
    //获取公告方案
    async noticeFang() {
      const res = fetch('/app/client/notice/plan/select/list')
        .then((response) => response.json())
        .catch((error) => {
          if (error.msg == '插件未购买') {
          }
        })
      return res
    },
    //获取渠道列表
    async channels(val?: any) {
      const res = await get({
        url: channel,
        data: {
          userId: val,
        },
      })
      return res
    },
    //获取渠道列表
    async channels1(val?: any) {
      const res = await get({
        url: channel,
        data: {
          userId: val,
        },
      })
      const list = {
        data: [
          {
            title: '流量池',
            key: -1,
            children: [],
          },
          {
            title: 'API',
            key: -2,
            children: [],
          },
        ],
      }
      res.data.forEach((element: any) => {
        const elementItem = {
          title: element.name,
          value: element.name,
          key: element.id,
        }
        if (element.api) {
          list.data[1].children.push(elementItem)
        } else {
          list.data[0].children.push(elementItem)
        }
      })
      return list
    },
    //获取系列列表
    async seriess(val?: any) {
      const res = await get({
        url: series,
        data: {
          channelIds: val,
        },
      })
      return res
    },

    //代理获取系列列表
    async userseriess(val?: any) {
      const res = await get({
        url: getUserSeries,
        data: {
          userId: val,
        },
      })
      return res
    },
    //获取渠道列表
    async getchannelList(val?: any) {
      const res = await get({
        url: getchannelList,
        data: {
          seriesIds: val,
        },
      })
      return res
    },
    //获取全部设备渠道列表
    async getDeviceChannel() {
      const res = await get({
        url: '/app/device/channel/get/all',
      })
      return res
    },

    //获取全部设备方案
    async getDeviceScheme() {
      const res = await get({
        url: '/app/device/scheme/get/all',
      })
      return res
    },
    //获取虚量
    async xuliangs() {
      const res = await get({ url: xuliangUrl })
      return res
    },
    //获取一卡一码内容模板
    async oneCardTemplate(val: any) {
      const res = await get({
        url: '/app/new/one/card/one/code/template/name/list',
        data: {
          classifyId: val,
        },
      })
      return res
    },
    //代理获取一卡一码内容模板
    async oneCardTemplateUser(val: any) {
      const res = await get({
        url: '/app/new/one/card/one/code/template/name/user/get/list',
        data: {
          classifyId: val,
        },
      })
      return res
    },
    //获取wifi频段
    async deviceBand() {
      const res = await get({
        url: '/app/release/device/get/wifi/band',
      })
      return res
    },

    //获取表头排序
    async getTitleSort(name: string) {
      const res = await get({ url: getTableDepartment, data: { name: name } })
      return res
    },
    //保存表头排序
    async setTitleSort(name: any) {
      const res = await post({ url: setTableDepartment, data: name })
      return res
    },
    //管理员列表
    async adminLists() {
      const res = await get({ url: adminList })
      return res
    },
    //客户列表
    async userLists() {
      const res = await get({ url: getUserListN })
      return returnFn(res, 'userName')
    },
    //一卡一码客户列表
    async userListOne() {
      const res = await get({ url: '/app/new/one/card/one/code/get/user' })
      return returnFn(res, 'userName')
    },
    getOperatorType(operator: any) {
      switch (operator) {
        case 0:
          return '移动'
        case 1:
          return '联通'
        case 2:
          return '电信'
        case 3:
          return '广电'
        default:
          return '未知'
      }
    },
    getGenderAndAge(idCard: any) {
      // 定义返回对象
      const result = {
        gender: null,
        age: null,
      }

      // 检查身份证号长度是否为 18 位
      if (idCard.length === 18) {
        // 获取出生日期信息
        const birthYear = parseInt(idCard.slice(6, 10))
        const birthMonth = parseInt(idCard.slice(10, 12))
        const birthDay = parseInt(idCard.slice(12, 14))

        // 获取当前日期
        const now = new Date()
        const currentYear = now.getFullYear()
        const currentMonth = now.getMonth() + 1
        const currentDay = now.getDate()

        // 计算年龄
        let age = currentYear - birthYear
        if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
          age--
        }
        result.age = age

        // 获取性别信息
        const genderCode = parseInt(idCard.slice(16, 17))
        if (genderCode % 2 === 0) {
          result.gender = '女'
        } else {
          result.gender = '男'
        }
        return result.gender + `/${result.age}岁`
      } else {
        return '未知'
      }
    },

    //导出文件
    downLoadPost(url: string, data: any, name: string) {
      Modal.warning({
        title: '导出提示',
        content: '文件导出中，请前往文件导出页面下载文件',
        cancelText: '文件导出',
        titleAlign: 'start',
        hideCancel: false,
        okText: '确定',
        onCancel() {
          if (window.location.pathname.split('/')[1] == 'children') {
            router.push('/children/log/excel')
          } else {
            router.push('/log/excel')
          }
        },
      })
      const res = Axios({
        method: 'post',
        url: url,
        responseType: 'blob',
        data: qs.stringify(data, { arrayFormat: 'repeat' }),
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      })
        .then((response) => {
          // console.log(response)
          // const blob = new Blob([response.data], {
          //   type: 'application/vnd.ms-excel; charset=UTF-8',
          // }) //处理文档流
          // const fileName = name + new Date().toLocaleString() + '.xlsx'
          // const elink = document.createElement('a')
          // elink.download = fileName
          // elink.style.display = 'none'
          // elink.href = URL.createObjectURL(blob)
          // document.body.appendChild(elink)
          // elink.click()
          // URL.revokeObjectURL(elink.href) // 释放URL 对象
          // document.body.removeChild(elink)
        })
        .catch((error) => {
          const file: any = new FileReader() //读取文件
          file.readAsText(error.response.data, 'utf-8') //读取文件，并设置编码格式为utf-8
          // eslint-disable-next-line prettier/prettier
          file.onload = function() {
            //在读取文件操作完成后触发
            const message = JSON.parse(file.result) //reader.result返回文件的内容，只在读取操作完成后有效
            Message.error(message.msg)
          }
        })
      return res
    },
    //导出文件
    downLoadPosts(url: string, data: any, name: string) {
      const res = Axios({
        method: 'post',
        url: url,
        responseType: 'blob',
        data: qs.stringify(data, { arrayFormat: 'repeat' }),
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      })
        .then((response) => {
          console.log(response)
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel; charset=UTF-8',
          }) //处理文档流
          const fileName = name + new Date().toLocaleString() + '.xlsx'
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        })
        .catch((error) => {
          const file: any = new FileReader() //读取文件
          file.readAsText(error.response.data, 'utf-8') //读取文件，并设置编码格式为utf-8
          // eslint-disable-next-line prettier/prettier
          file.onload = function() {
            //在读取文件操作完成后触发
            const message = JSON.parse(file.result) //reader.result返回文件的内容，只在读取操作完成后有效
            Message.error(message.msg)
          }
        })
      return res
    },
    //导出文件
    downLoad(url: string, data: any, name: string) {
      if (!name.includes('导出日志列表')) {
        Modal.warning({
          title: '导出提示',
          content: '文件导出中，请前往文件导出页面下载文件',
          cancelText: '文件导出',
          titleAlign: 'start',
          hideCancel: false,
          okText: '确定',
          onCancel() {
            if (window.location.pathname.split('/')[1] == 'children') {
              router.push('/children/log/excel')
            } else {
              router.push('/log/excel')
            }
          },
        })
      }
      const date = '?' + qs.stringify(data, { arrayFormat: 'repeat' })
      const res = Axios({
        method: 'GET',
        url: url + date,
        responseType: 'blob',
      })
        .then((response) => {
          if (name.includes('导出日志列表')) {
            const blob = new Blob([response.data], {
              type: 'application/vnd.ms-excel; charset=UTF-8',
            }) //处理文档流
            const fileName = name + new Date().toLocaleString() + '.xlsx'
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          }
        })
        .catch((error) => {
          const file: any = new FileReader() //读取文件
          file.readAsText(error.response.data, 'utf-8') //读取文件，并设置编码格式为utf-8
          // eslint-disable-next-line prettier/prettier
          file.onload = function() {
            //在读取文件操作完成后触发
            const message = JSON.parse(file.result) //reader.result返回文件的内容，只在读取操作完成后有效
            Message.error(message.msg)
          }
        })
      return res
    },
    //导出文件
    downLoads(url: string, data: any, name: string) {
      const date = '?' + qs.stringify(data, { arrayFormat: 'repeat' })
      const res = Axios({
        method: 'GET',
        url: url + date,
        responseType: 'blob',
      })
        .then((response) => {
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel; charset=UTF-8',
          }) //处理文档流
          let fileName = ''
          if (name == '打款文件') {
            fileName = name + new Date().toLocaleString() + '.xls'
          } else {
            fileName = name + new Date().toLocaleString() + '.xlsx'
          }

          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        })
        .catch((error) => {
          const file: any = new FileReader() //读取文件
          file.readAsText(error.response.data, 'utf-8') //读取文件，并设置编码格式为utf-8
          // eslint-disable-next-line prettier/prettier
              file.onload = function() {
            //在读取文件操作完成后触发
            const message = JSON.parse(file.result) //reader.result返回文件的内容，只在读取操作完成后有效
            Message.error(message.msg)
          }
        })
      return res
    },
  },
})

//处理返回数据
async function returnFn(list: any, keys: any, keyName?: any) {
  const returnList = { data: [] }
  // 数据分批
  const totalBatches = Math.ceil(list.data.length / 1000)
  for (let batch = 0; batch < totalBatches; batch++) {
    const start = batch * 1000
    const end = Math.min((batch + 1) * 1000, list.data.length)
    const batchData = list.data.slice(start, end)
    const processedBatch: any = await Promise.all(
      batchData.map(async (item: any) => {
        const obj = {
          value: keyName ? item[keyName] : item.id,
          label: item[keys],
        }
        return obj
      })
    )
    returnList.data.push(...processedBatch)
  }

  return returnList
}

export default useCommonStore

export function useCommonStoreContext() {
  return useCommonStore(store)
}
